/*
	Copyright (c) 2004-2009, The Dojo Foundation All Rights Reserved.
	Available via Academic Free License >= 2.1 OR the modified BSD license.
	see: http://dojotoolkit.org/license for details
*/

/*
	This is a compiled version of Dojo, built for deployment and not for
	development. To get an editable version, please visit:

		http://dojotoolkit.org

	for documentation and information on getting the source.
*/

if(!dojo._hasResource["lucid.apps.Messenger._base"]){ //_hasResource checks added by build. Do not use _hasResource directly in your code.
dojo._hasResource["lucid.apps.Messenger._base"] = true;
dojo.provide("lucid.apps.Messenger._base");




dojo.declare("lucid.apps.Messenger", lucid.apps._App, {
	init: function(args){
        this.windows = [];
    	var win = this.makeBuddyListWin(); //OH YA WE ARE DRAW UI
        this.setListener();
        this.initSounds();
        this.timer = setInterval(dojo.hitch(this, "updateStatus"), 10000);
        this.updateStatus();
        win.show();
    },
    kill: function(stright){
        dojo.forEach(this.windows, function(win){
            if(!win.closed)
		        win.close();
		});
        this.cleanupSounds();
		this.removeListener(); //Tell crosstalk we are no longer intrested in recieving events.
        clearInterval(this.timer);
	}
});


}

if(!dojo._hasResource["lucid.apps.Messenger.store"]){ //_hasResource checks added by build. Do not use _hasResource directly in your code.
dojo._hasResource["lucid.apps.Messenger.store"] = true;
dojo.provide("lucid.apps.Messenger.store");

dojo.extend(lucid.apps.Messenger, {
    buddyStore: null,
    makeBuddyStore: function(){
        if(this.buddyStore) return this.buddyStore;
        var store = this.buddyStore = new lucid.Registry({
            name: "buddyList",
            appname: this.sysname,
            data: {
                identifier: "id",
                label: "username",
                items: [
                    //sample item:
                    //{id: 0, userid: 1, username: "admin"}
                ]
            }
        });
        return store;
    },
    addBuddy: function(info){
		var strings = dojo.i18n.getLocalization("lucid.apps.Messenger", "messenger");
        if(!info.exists){
            return lucid.dialog.notify({type: "error", message: strings.noUser});
        }
        this.buddyStore.newItem({
            id: info.id,
            username: info.username,
            logged: info.logged
        });
        this.buddyStore.save();
    },
    updateStatus: function(){
        var store = this.buddyStore;
        store.fetch({
            query: {id: "*"},
            onComplete: function(items){
                var params = [];
                dojo.forEach(items, function(item){
                    params.push({
                        id: store.getValue(item, "id")
                    });
                }, this);
                lucid.user.get({
                    users: params,
                    onComplete: function(users){
                        dojo.forEach(users, function(user){
                            store.fetch({
                                query: {id: user.id},
                                onItem: function(item){
                                    store.setValue(item, "logged", !!parseInt(user.logged));
                                }
                            });
                        }, this);
                    }
                });
            }
        });
    }
});

}

if(!dojo._hasResource["lucid.apps.Messenger.widget.AddBuddyForm"]){ //_hasResource checks added by build. Do not use _hasResource directly in your code.
dojo._hasResource["lucid.apps.Messenger.widget.AddBuddyForm"] = true;
dojo.provide("lucid.apps.Messenger.widget.AddBuddyForm");




dojo.declare("lucid.apps.Messenger.widget.AddBuddyForm", dijit.form.Form, {
    widgetsInTemplate: true,
    templateString: null,
	strings: "",
    templateString:"<form dojoAttachPoint='containerNode' dojoAttachEvent='onreset:_onReset,onsubmit:_onSubmit'>\n   <label for=\"${id}_username\">${strings.buddyUsername}</label>\n   <input dojoType=\"dijit.form.TextBox\" name=\"username\" />\n   <div style=\"text-align: right; margin-top: 5px;\">\n      <div dojoType=\"dijit.form.Button\" class=\"dijitInline\" label=\"${strings.cancel}\" dojoAttachEvent=\"onClick:onCancel\"></div>\n      <div dojoType=\"dijit.form.Button\" class=\"dijitInline\" iconClass=\"icon-22-actions-list-add\" label=\"${strings.add}\" dojoAttachEvent=\"onClick:onSubmit\"></div>\n   </div>\n</form> \n",
    onSubmit: function(){
    },
    onCancel: function(){
    },
	constructor: function(){
		this.strings = dojo.i18n.getLocalization("lucid.apps.Messenger", "messenger");
	}
});

}

if(!dojo._hasResource["lucid.apps.Messenger.widget.MessageBox"]){ //_hasResource checks added by build. Do not use _hasResource directly in your code.
dojo._hasResource["lucid.apps.Messenger.widget.MessageBox"] = true;
dojo.provide("lucid.apps.Messenger.widget.MessageBox");



dojo.declare("lucid.apps.Messenger.widget.MessageBox", [dijit._Widget, dijit._Templated, dijit._Contained], {
    templateString:"<div style=\"height: 20px;\">\n    <!--<div dojoType=\"dijit.layout.BorderContainer\" gutters=\"false\" style=\"position: absolute; top: 0px; left: 0px; width: 100%; height: 20px;\">\n        <div dojoType=\"dijit.layout.ContentPane\" region=\"center\">-->\n            <input dojoType=\"dijit.form.TextBox\" dojoAttachPoint=\"inputBox\" style=\"width: 100%\" /> \n        <!--</div>\n        <div dojoType=\"dijit.layout.ContentPane\" region=\"right\" style=\"width: 80px\">\n            <div dojoType=\"dijit.form.Button\" dojoAttachPoint=\"sendButton\" label=\"Send\" dojoAttachEvent=\"onClick:_onClick\"></div>\n        </div>\n    </div>-->\n</div>\n\n",
    widgetsInTemplate: true,
    postCreate: function(){
        this.inherited(arguments);
        dojo.connect(this.inputBox.domNode, "onkeyup", this, "_onKey");
    },
    onSend: function(value){
        
    },
    _onSend: function(value){
        if(value != "")
            this.onSend(value);
        this.inputBox.attr("value", "");
    },
    _onKey: function(e){
        if(e.keyCode == dojo.keys.ENTER)
            this._onSend(this.inputBox.attr("value"));
    },
    _onClick: function(){
        this._onSend(this.inputBox.attr("value"));
    }
});

}

if(!dojo._hasResource["lucid.apps.Messenger.ui"]){ //_hasResource checks added by build. Do not use _hasResource directly in your code.
dojo._hasResource["lucid.apps.Messenger.ui"] = true;
dojo.provide("lucid.apps.Messenger.ui");










dojo.extend(lucid.apps.Messenger, {
    buddyListWin: null,
    selectedBuddy: null,
    removeBuddyButton: null,
    unameUi: {},
    makeBuddyListWin: function(){
		var strings = dojo.i18n.getLocalization("lucid.apps.Messenger", "messenger");
        if(this.buddyListWin && !this.buddyListWin.closed) return this.BuddyListWin;
        var win = this.buddyListWin = new lucid.widget.Window({
            title: strings.contactList,
            iconClass: this.iconClass,
            width: "220px",
            height: "400px",
            onClose: dojo.hitch(this, "kill")
        });
        this.windows.push(win);
        this.unameUi = {};

        var store = this.makeBuddyStore();
        
        var toolbar = new dijit.Toolbar({
            region: "top"
        });
        
        var addButton = new dijit.form.Button({
            label: strings.addUser,
            iconClass: "icon-16-actions-list-add",
            onClick: dojo.hitch(this, "drawAddBuddyDialog"),
            getIconClass: function(item, opened){
                return "icon-16-apps-system-users";
            }
        });
        toolbar.addChild(addButton);
        
        var removeButton = this.removeBuddyButton = new dijit.form.Button({
            label: strings.removeUser,
            iconClass: "icon-16-actions-list-remove",
            disabled: true,
            onClick: dojo.hitch(this, function(){
                if(!this.selectedBuddy) return;
                store.deleteItem(this.selectedBuddy);
                store.save();
                this.selectedBuddy = null;
            })
        });

        toolbar.addChild(removeButton);

        win.addChild(toolbar);

        var model = new dijit.tree.ForestStoreModel({
            store: store,
            rootLabel: strings.contacts
        });

        var tree = new dijit.Tree({
            model: model,
            region: "center",
            getIconClass: function(item, opened){
                var iconClass = "";
                if(store.isItem(item) && store.hasAttribute(item, "logged")){
                    iconClass = store.getValue(item, "logged") ? "icon-16-apps-system-users" : "icon-16-actions-system-log-out";
                    return iconClass;
                }
                return (!item || this.model.mayHaveChildren(item)) ? (opened ? "dijitFolderOpened" : "dijitFolderClosed") : iconClass;
            },

            onClick: dojo.hitch(this, function(item){
                if(this.selectedBuddy == item){
                    var imWin = this.makeImWindow(item);
                    if(imWin.shown) imWin.bringToFront();
                    else imWin.show();
                    return;
                }
                this.selectedBuddy = item;
                this.removeBuddyButton.attr("disabled", false);
            })
        });

        win.addChild(tree);
        tree.startup();
        return win;
    },
    makeImWindow: function(item){
        var store = this.buddyStore;
        var uiSlot = this.unameUi[store.getValue(item, "id")];
        if(uiSlot && !uiSlot.win.closed)
            return uiSlot.win.bringToFront();
        var win = new lucid.widget.Window({
            title: store.getValue(item, "username"),
            width: "250px",
            height: "250px"
        });
        
        var messagePane = new dijit.layout.ContentPane({
            region: "center"
        });

        win.addChild(messagePane);

        var inputBox = new lucid.apps.Messenger.widget.MessageBox({
            region: "bottom",
            onSend: dojo.hitch(this, function(msg){
                this.sendMessage(store.getValue(item, "id"), msg);
            })
        }); 
        
        win.addChild(inputBox);
        
        this.unameUi[store.getValue(item, "id")] = {
            msgPane: messagePane,
            win: win,
            username: store.getValue(item, "username")
        };
        this.windows.push(win);
        return win;
    },
    pushMsg: function(uid, msg, local){
        var uiSlot = this.unameUi[uid];
        if(uiSlot && uiSlot.win && !uiSlot.win.closed){
            var node = uiSlot.msgPane.domNode;
            var line = this.msgToNode(uiSlot.username, msg, local);
            node.appendChild(line);
            dojox.fx.smoothScroll({
				node: line,
				win: node,
				duration: 500,
				easing:dojo.fx.easing.easeOut,
                onEnd: function(){
                    node.scrollTop = node.scrollHeight+node.offsetHeight;
                    node.scrollLeft = 0;
                }
			}).play();
        }
        else {
            var store = this.buddyStore;
            store.fetch({
                query: {id: uid},
                onComplete: dojo.hitch(this, function(items){
                    if(items.length == 0){
                        //add the user who sent this to the buddy list
                        lucid.user.get({
                            id: uid,
                            onComplete: dojo.hitch(this, function(info){
                                var item = this.addBuddy(info);
                                var win = this.makeImWindow(item);
                                this.pushMsg(uid, msg);
                                win.show();
                            })
                        });
                    }else{
                        var win = this.makeImWindow(items[0]);
                        this.pushMsg(uid, msg);
                        win.show();
                    }
                })
            });
        }
    },
    msgToNode: function(username, message, local){
        var div = document.createElement("div");
        
        var timeSpan = document.createElement("span");
        var timestamp = dojo.date.locale.format(new Date());
        timeSpan.innerHTML = "("+timestamp+") ";
        dojo.style(timeSpan, {
            color: local ? "blue" : "red"
        });
        div.appendChild(timeSpan);

        
        var nameSpan = document.createElement("span");
        div.appendChild(nameSpan);

        dojo.style(nameSpan, {
            fontWeight: "bold",
            color: local ? "blue" : "red"
        });

        var msgSpan = document.createElement("span");
        lucid.textContent(msgSpan, message);
        var message = msgSpan.innerHTML.split(" ");
        var fixedMessage = [];
        dojo.forEach(message, function(word){
            if(dojox.validate.isUrl(word) && word.indexOf("://") != -1)
                fixedMessage.push("<a href=\""+word.replace("\"", "\\\"")+"\">"+word+"</a>");
            else
                fixedMessage.push(word);
        });
        msgSpan.innerHTML = fixedMessage.join(" ");

        dojo.query("a", msgSpan).forEach(function(node){
			dojo.connect(node, "onclick", node, function(e){
				if(!e.shiftKey
				&& !e.ctrlKey){
					lucid.app.launchHandler(null, {url: this.href}, "text/x-uri");
					e.preventDefault();
				}
            })
		});

        div.appendChild(msgSpan);
        
        if(local){
            this.getCurrentUsername(function(name){
                lucid.textContent(nameSpan, name+": ");
            });
        }else{
            lucid.textContent(nameSpan, username+": ");
        }
        return div;
    },
    drawAddBuddyDialog: function(){
		var strings = dojo.i18n.getLocalization("lucid.apps.Messenger", "messenger");
        var win = new lucid.widget.Window({
            title: strings.addUser,
            width: "350px",
            height: "200px"
        });
        
        form = new lucid.apps.Messenger.widget.AddBuddyForm({
            onSubmit: dojo.hitch(this, function(){
                var values = form.getValues();
                lucid.user.get({
                    username: values.username,
                    onComplete: dojo.hitch(this, "addBuddy")
                });
                win.close();
                return false;
            }),
            onCancel: dojo.hitch(win, "close"),
            region: "center"
        });
        win.addChild(form);
        this.windows.push(win);
        win.show();
    },
    wrapWid: function(widget){
        var div = document.createElement("div");
        div.appendChild(widget.domNode);
        return div;
    }
});

}

if(!dojo._hasResource["lucid.apps.Messenger.io"]){ //_hasResource checks added by build. Do not use _hasResource directly in your code.
dojo._hasResource["lucid.apps.Messenger.io"] = true;
dojo.provide("lucid.apps.Messenger.io");

dojo.extend(lucid.apps.Messenger, {
    listener: null,
    currentUsername: null,
    setListener: function(){
        this.listener = lucid.crosstalk.subscribe("IM", dojo.hitch(this, "recieveMessage"), this.instance); 
    },
    removeListener: function(){
        lucid.crosstalk.unsubscribe(this.listener);
    },
    sendMessage: function(uid, msg){
        this.pushMsg(uid, msg, true);
        lucid.crosstalk.publish("IM", {text: msg}, uid, this.sysname, null, dojo.hitch(this, function(messageID){
            var kd = setTimeout(dojo.hitch(this, function(){
                this.checkSent(messageID, uid);
            }), 2000);
        }));
        this.playSend();
    },
    checkSent: function(id, uid){
		var strings = dojo.i18n.getLocalization("lucid.apps.Messenger", "messenger");
	    lucid.crosstalk.exists(id, dojo.hitch(this, function(notsent){
		    if(notsent){
			    this.pushMsg(uid, strings.userOffline);
    		}
	    }));
    },
    recieveMessage: function(msg){
        var uid = msg._crosstalk.sender;        
        this.pushMsg(uid, msg.text, false);
        this.playReceive();
    },
    getCurrentUsername: function(cback){
        if(this.currentUsername) cback(this.currentUsername);
        lucid.user.get({onComplete: dojo.hitch(this, function(data){
            this.currentUsername = data.username;
            cback(this.currentUsername);
        })});
    }
});

}

if(!dojo._hasResource["lucid.apps.Messenger.sound"]){ //_hasResource checks added by build. Do not use _hasResource directly in your code.
dojo._hasResource["lucid.apps.Messenger.sound"] = true;
dojo.provide("lucid.apps.Messenger.sound");

dojo.extend(lucid.apps.Messenger, {
    sounds: {
        send: null,
        receive: null
    },
    initSounds: function(){
        var s = this.sounds = {};
        s.send = new lucid.Sound({
            src: dojo.moduleUrl("lucid.apps.Messenger.resources", "send.mp3").uri
        });
        s.receive = new lucid.Sound({
            src: dojo.moduleUrl("lucid.apps.Messenger.resources", "receive.mp3").uri
        });
        s.send.stop();
        s.receive.stop();
        
    },
    cleanupSounds: function(){
        for(var s in this.sounds){
            this.sounds[s].destroy();
        }
    },
    playSend: function(){
        var s = this.sounds.send;
        s.stop();
        s.play();
    },
    playReceive: function(){
        var s = this.sounds.receive;
        s.stop();
        s.play();
    }
});

}

if(!dojo._hasResource["lucid.apps.Messenger"]){ //_hasResource checks added by build. Do not use _hasResource directly in your code.
dojo._hasResource["lucid.apps.Messenger"] = true;
dojo.provide("lucid.apps.Messenger");









}


dojo.i18n._preloadLocalizations("lucid.apps.nls.Messenger", ["ROOT","en","en-gb","en-us","es","es-es","fr","fr-fr","xx"]);
